<template>
  <page-header-wrapper>
    <a-card :bordered="false">
      <a-descriptions title="模板名称">
        <a-descriptions-item>
          <span class="templateName">{{ tempDtl.templateName ?? '—' }} </span>
          <a-button @click="previewVisible = true">预览模板</a-button>
        </a-descriptions-item>
      </a-descriptions>
      <a-divider style="margin-bottom: 32px" />
      <a-descriptions title="爱签参数">
        <a-descriptions-item>
          <a-button type="primary" @click="_addParam">新增参数</a-button>
          <div class="paramsList">
            <div class="paramsItem" v-for="(item, index) in tempDtl.paramsList" :key="item.paramName">
              <div class="closeBtn" @click="tempDtl.paramsList.splice(index, 1)">
                <a-icon type="close-circle" style="color: rgb(245, 34, 45)" />
              </div>
              <div class="paramName">{{ item.paramName }}</div>
              <div class="paramType">{{ paramTypeMap[item.paramType] }}</div>
            </div>
          </div>
        </a-descriptions-item>
      </a-descriptions>
      <a-descriptions title="签约步骤" width="100%"></a-descriptions>
      <div class="stepList">
        <div class="stepItem" v-for="(item, index) in tempDtl.stepList" :key="item.stepTitle">
          <div class="stepTitle">
            <span class="stepSeq">{{ `第${index + 1}页` }}</span>
            <a-input class="iptText" v-model="item.stepTitle"></a-input>
            <a-icon type="delete" style="color: rgb(245, 34, 45)" @click="_delStepItem(index)" />
          </div>
          <div class="moduleList">
            <div class="moduleItem" v-for="(val, idx) in item.moduleList" :key="val.moduleName">
              <div class="moduleTitle">
                <span class="stepSeq">{{ `第${idx + 1}项` }}</span>
                <a-input class="iptText" v-model="val.moduleName"></a-input>
                <a-icon type="delete" style="color: rgb(245, 34, 45)" @click="_delModuleItem(index, idx)" />
              </div>
              <div class="itemList">
                <div class="itemList__header">
                  <div class="itemList__header__item">名称</div>
                  <div class="itemList__header__item">类型</div>
                  <div class="itemList__header__item itemList__header__item1">是否必填</div>
                  <div class="itemList__header__item">绑定爱签参数</div>
                </div>
                <div class="itemList__item" v-for="(v, i) in val.itemList" :key="`${v.itemName}-${i}`">
                  <a-input class="iptText" v-model="v.itemName" disabled></a-input>
                  <a-select class="iptText" v-model="v.itemType" disabled>
                    <a-select-option :value="1"> 单行文本 </a-select-option>
                    <a-select-option :value="2"> 多行文本 </a-select-option>
                    <a-select-option :value="3"> 金额及大写 </a-select-option>
                    <a-select-option :value="4"> 身份证号码 </a-select-option>
                    <a-select-option :value="5"> 手机号码 </a-select-option>
                    <a-select-option :value="6"> 日期 </a-select-option>
                    <a-select-option :value="7"> 选择框 </a-select-option>
                    <a-select-option :value="8"> 数字及大写 </a-select-option>
                    <a-select-option :value="9"> 年月 </a-select-option>
                    <a-select-option :value="10"> 文件 </a-select-option>
                  </a-select>
                  <a-select class="iptText1" placeholder="是否必填" v-model="v.isCanEmpty" disabled>
                    <a-select-option :value="0"> 否 </a-select-option>
                    <a-select-option :value="1"> 是 </a-select-option>
                  </a-select>
                  <a-select class="iptText" placeholder="请选择爱签参数（非必填）" v-model="v.bindParamName">
                    <a-select-option :value="o.paramName" v-for="o in tempDtl.paramsList" :key="o.paramName">
                      {{ o.paramName }}
                    </a-select-option>
                  </a-select>
                  <span class="handleBtns" v-if="val.moduleType === 5">
                    <a><a-icon type="edit" @click="_editItem(index, idx, i)" /></a>&ensp;&ensp;
                    <a><a-icon type="delete" style="color: rgb(245, 34, 45)" @click="_delItem(index, idx, i)" /></a>
                  </span>
                </div>
                <div class="itemList__item" v-if="val.moduleType === 5">
                  <a><a-button icon="plus" type="primary" @click="_addItem(index, idx)">新增参数</a-button></a>
                </div>
              </div>
            </div>
            <div class="addModuleItem">
              <a><a-button icon="plus" type="primary" @click="_addModuleItem(index)">新增参数项</a-button></a>
            </div>
          </div>
        </div>
      </div>
      <div class="footer">
        <a-button class="handleBtn" shape="round" @click="_addStepItem">新增一页</a-button>
        <a-button class="handleBtn" shape="round" type="primary" @click="_submitForm">提交</a-button>
      </div>

      <a-modal :visible="previewVisible" centered width="60%" :footer="null" @cancel="previewVisible = false">
        <div class="previewWrap">
          <iframe :src="tempDtl.templateUrl" frameborder="0" width="90%" height="600px"></iframe>
        </div>
      </a-modal>
      <create-params-form
        ref="createForm"
        :visible="visible"
        :loading="confirmLoading"
        @cancel="handleCancel"
        @ok="handleOk"
      />
      <create-temp-module-form
        ref="createTempModuleForm"
        :visible="tempModuleVisible"
        :paramsList="tempDtl.paramsList"
        :loading="confirmLoading"
        @cancel="_cancelTempModule"
        @ok="_submitTempModule"
      />
      <create-temp-item-form
        ref="createTempItemForm"
        :visible="tempItemVisible"
        :paramsList="tempDtl.paramsList"
        :loading="confirmLoading"
        :model="mdl"
        @cancel="_cancelTempItem"
        @ok="_submitTempItem"
      />
    </a-card>
  </page-header-wrapper>
</template>

<script>
import { STable } from '@/components'
import { getTempDtl, configTemp } from '@/api/custContractManage'
import CreateParamsForm from '../modules/CreateParamsForm'
import CreateTempModuleForm from '../modules/CreateTempModuleForm'
import CreateTempItemForm from '../modules/CreateTempItemForm'
const paramTypeMap = {
  1: '单行文本',
  2: '多行文本',
  3: '日期',
  4: '身份证号码',
  5: '企业签署区',
  6: '个人签署区',
  7: '签署日期'
}

const moduleTypeMap = {
  1: '企业签约',
  2: '个人签约',
  3: '价格信息',
  4: '附加信息',
  5: '自定义信息'
}

const priceArr = [
  {
    isCanEmpty: 0,
    itemName: '总额',
    itemSeq: 1,
    itemType: 3
  },
  {
    isCanEmpty: 0,
    itemName: '定金',
    itemSeq: 2,
    itemType: 3
  },
  {
    isCanEmpty: 0,
    itemName: '分期选择',
    itemOptions: '3期#*#6期#*#12期#*#24期',
    itemSeq: 3,
    itemType: 7
  },
  {
    isCanEmpty: 0,
    itemName: '还款日',
    itemOptions: '次月当日#*#次月5日#*#次月15日#*#次月25日',
    itemSeq: 4,
    itemType: 7
  }
]

const partArr = [
  {
    isAppendice: '1',
    isCanEmpty: 1,
    itemName: '正面人像',
    itemSeq: 1,
    itemType: 10
  },
  {
    isAppendice: '1',
    isCanEmpty: 1,
    itemName: '反面国徽',
    itemSeq: 2,
    itemType: 10
  },
  {
    isCanEmpty: 0,
    itemName: '姓名',
    itemSeq: 3,
    itemType: 1
  },
  {
    isCanEmpty: 0,
    itemName: '身份证号',
    itemSeq: 4,
    itemType: 4
  },
  {
    isCanEmpty: 0,
    itemName: '联系电话',
    itemSeq: 5,
    itemType: 5
  },
  {
    isCanEmpty: 0,
    itemName: '地址',
    itemSeq: 6,
    itemType: 1
  }
]

const extraInfoArr = [{ isCanEmpty: 1, itemName: '附加信息', itemSeq: 1, itemType: 2 }]

export default {
  components: {
    STable,
    CreateParamsForm,
    CreateTempModuleForm,
    CreateTempItemForm
  },
  data () {
    return {
      templateNo: '',
      paramTypeMap,
      tempDtl: {},
      merchantId: '',
      contractNums: '',
      curTempNo: '',
      custContractDtl: {},
      mdl: null,
      previewVisible: false,
      visible: false,
      tempModuleVisible: false,
      tempItemVisible: false,
      confirmLoading: false,
      curStepIdx: -1,
      curModuleIdx: -1,
      curGrandsonIdx: -1,
      isEdit: false,
      columns: [
        {
          title: '账单名称',
          dataIndex: 'billName',
          key: 'billName',
          align: 'center'
        },
        {
          title: '账单类型',
          dataIndex: 'billType',
          key: 'billType',
          scopedSlots: { customRender: 'billType' },
          align: 'center'
        },
        {
          title: '账单金额（单位：元）',
          dataIndex: 'repaymentAmount',
          key: 'repaymentAmount',
          align: 'center'
        },
        {
          title: '应还款时间',
          dataIndex: 'shouldRepaymentTime',
          key: 'shouldRepaymentTime',
          align: 'center'
        },
        {
          title: '实还款时间',
          dataIndex: 'actualRepaymentTime',
          key: 'actualRepaymentTime',
          align: 'center'
        },
        {
          title: '还款状态',
          dataIndex: 'repaymentStatus',
          key: 'repaymentStatus',
          scopedSlots: { customRender: 'repaymentStatus' },
          align: 'center'
        },
        {
          title: '资方分账金额',
          dataIndex: 'capitalAllocateAmount',
          key: 'capitalAllocateAmount',
          customRender: (text) => text ?? '—',
          align: 'center'
        }
      ]
    }
  },
  filters: {
    repaymentStatusFilter (text) {
      const repaymentStatusMap = {
        1: '正常',
        2: '逾期',
        3: '结清'
      }
      return repaymentStatusMap[text]
    },
    repaymentDayFilter (text) {
      const repaymentDayMap = {
        1: '次月今日',
        2: '次月5日',
        3: '次月15日',
        4: '次月25日',
        5: '一周后',
        6: '次月25日'
      }
      return repaymentDayMap[text]
    },
    capitalContractStatusFilter (text) {
      const capitalContractStatusMap = {
        0: '未打包',
        1: '已打包',
        2: '已结清',
        4: '已冻结'
      }
      return capitalContractStatusMap[text]
    },
    repaymentStatus1Filter (text) {
      const repaymentStatusMap = {
        0: '未到期',
        12: '逾期未付',
        21: '正常支付',
        22: '逾期支付',
        5: '已作废',
        6: '标记支付'
      }
      return repaymentStatusMap[text]
    }
  },
  computed: {
    title () {
      return this.$route.meta.title
    }
  },
  methods: {
    /**
     * 新增一页
     */
    _addStepItem () {
      this.tempDtl.stepList.push({
        stepTitle: '',
        stepSeq: this.tempDtl.stepList.length + 1,
        moduleList: []
      })
    },
    /**
     * 删除某一页
     */
    _delStepItem (curIdx) {
      this.$warning({
        title: '删除提示',
        content: `确认删除${this.tempDtl.stepList[curIdx].stepTitle}?`,
        okText: '确认',
        cancelText: '取消',
        destroyOnClose: true,
        closable: true,
        onOk: () => {
          this.tempDtl.stepList.splice(curIdx, 1)
        }
      })
    },
    /**
     * 新增参数项
     */
    _addModuleItem (curIdx) {
      const form = this.$refs.createTempModuleForm.form
      form.resetFields()
      this.tempModuleVisible = true
      this.curStepIdx = curIdx
    },
    /**
     * 删除某一项
     */
    _delModuleItem (curIdx, curChildIdx) {
      this.$warning({
        title: '删除提示',
        content: `确认删除${this.tempDtl.stepList[curIdx].moduleList[curChildIdx].moduleName}?`,
        okText: '确认',
        cancelText: '取消',
        destroyOnClose: true,
        closable: true,
        onOk: () => {
          this.tempDtl.stepList[curIdx].moduleList.splice(curChildIdx, 1)
        }
      })
    },
    /**
     * 新增参数
     */
    _addItem (curIdx, curChildIdx) {
      const form = this.$refs.createTempItemForm.form
      form.resetFields()
      this.mdl = null
      this.isEdit = false
      this.tempItemVisible = true
      this.curStepIdx = curIdx
      this.curModuleIdx = curChildIdx
    },
    /**
     * 修改某一项参数
     */
    _editItem (curIdx, curChildIdx, curGrandsonIdx) {
      this.isEdit = true
      this.tempItemVisible = true
      this.curStepIdx = curIdx
      this.curModuleIdx = curChildIdx
      this.curGrandsonIdx = curGrandsonIdx
      this.mdl = this.tempDtl.stepList[curIdx].moduleList[curChildIdx].itemList[curGrandsonIdx]
      this.mdl.isAppendice = this.mdl.isAppendice === 1
      this.mdl.isCanEmpty = this.mdl.isCanEmpty === 1
    },
    /**
     * 删除某一参数
     */
    _delItem (curIdx, curChildIdx, curGrandsonIdx) {
      this.$warning({
        title: '删除提示',
        content: `确认删除${this.tempDtl.stepList[curIdx].moduleList[curChildIdx].itemList[curGrandsonIdx].itemName}?`,
        okText: '确认',
        cancelText: '取消',
        destroyOnClose: true,
        closable: true,
        onOk: () => {
          this.tempDtl.stepList[curIdx].moduleList[curChildIdx].itemList.splice(curGrandsonIdx, 1)
        }
      })
    },
    /**
     * 新增爱签参数
     */
    _addParam () {
      this.visible = true
    },
    /**
     * 提交新增参数
     */
    handleOk () {
      const form = this.$refs.createForm.form
      this.confirmLoading = true
      form.validateFields((errors, values) => {
        if (!errors) {
          this.visible = false
          this.tempDtl.paramsList.push(values)
        }
      })
    },
    /**
     * 取消新增参数
     */
    handleCancel () {
      this.visible = false
    },
    /**
     * 取消新增项目
     */
    _cancelTempModule () {
      this.tempModuleVisible = false
      this.curStepIdx = -1
    },
    /**
     * 提交新增项目
     */
    _submitTempModule () {
      const form = this.$refs.createTempModuleForm.form
      form.validateFields((errors, values) => {
        const moduleItem = {
          moduleName: '',
          moduleSeq: '',
          moduleType: '',
          bindParamName: '',
          itemList: []
        }
        switch (values.moduleType) {
          case 1:
            moduleItem.itemList = partArr
            break
          case 2:
            moduleItem.itemList = partArr
            break
          case 3:
            moduleItem.itemList = priceArr
            break
          case 4:
            moduleItem.itemList = extraInfoArr
            break
          default:
            break
        }
        if (!errors) {
          this.tempModuleVisible = false
          this.tempDtl.stepList[this.curStepIdx].moduleList.push({
            ...moduleItem,
            ...values,
            moduleName: values.moduleType === 5 ? values.moduleName : moduleTypeMap[values.moduleType],
            moduleSeq: this.tempDtl.stepList[this.curStepIdx].moduleList.length + 1
          })
        }
      })
    },
    /**
     * 取消新增项目子项
     */
    _cancelTempItem () {
      this.tempItemVisible = false
      this.curStepIdx = -1
      this.curModuleIdx = -1
      this.curGrandsonIdx = -1
    },
    /**
     * 提交新增项目子项
     */
    _submitTempItem () {
      const form = this.$refs.createTempItemForm.form
      form.validateFields((errors, values) => {
        values.isAppendice = values.isAppendice ? 1 : 0
        values.isCanEmpty = values.isCanEmpty ? 1 : 0

        if (!errors) {
          this.tempItemVisible = false
          if (this.isEdit) {
            this.tempDtl.stepList[this.curStepIdx].moduleList[this.curModuleIdx].itemList[this.curGrandsonIdx] = {
              ...values
            }
          } else {
            this.tempDtl.stepList[this.curStepIdx].moduleList[this.curModuleIdx].itemList.push({
              ...values
            })
          }
        }
      })
    },
    /**
     * 提交表单
     */
    _submitForm () {
      const paramsData = {
        templateNo: this.templateNo,
        paramsList: this.tempDtl.paramsList,
        stepList: this.tempDtl.stepList
      }
      let isReturn = false
      this.tempDtl.stepList.forEach((item, index) => {
        if (isReturn) return false
        if (!item.stepTitle) {
          isReturn = true
          this.$message.warn('请检查表单信息，步骤名称不能为空')
          return false
        }
        if (!item.moduleList.length) {
          isReturn = true
          this.$message.warn('请检查表单信息，表单参数项不能为空')
          return false
        }
        item.moduleList.forEach((val, idx) => {
          if (!val.itemList.length) {
            isReturn = true
            this.$message.warn('请检查表单信息，表单参数不能为空')
            return false
          }
        })
      })

      if (isReturn) {
        return false
      }

      configTemp(paramsData)
        .then((res) => {
          this.$message.info('提交成功')
          this.getTempInfo()
        })
        .catch((e) => {})
    },
    getTempInfo () {
      getTempDtl({ templateNo: this.templateNo })
        .then((res) => {
          this.tempDtl = res.result
        })
        .catch((e) => {})
    }
  },
  mounted () {
    const { templateNo } = this.$route.params
    this.templateNo = templateNo
    this.getTempInfo()
  }
}
</script>

<style lang="less" scoped>
.templateName {
  margin-right: 10px;
}
.paramsList {
  display: flex;
  align-items: center;
  flex-wrap: wrap;
  padding: 20px 0;
  .paramsItem {
    position: relative;
    width: 150px;
    height: 90px;
    padding: 12px;
    margin: 0 12px 20px 0;
    border: 1px solid #eee;
    border-radius: 10px;
    box-sizing: border-box;
    .paramName {
      font-size: 16px;
      font-weight: 600;
      margin: 0 0 12px;
      color: #333;
    }
    .paramType {
      font-size: 14px;
      color: #666;
    }
    .closeBtn {
      position: absolute;
      right: -4px;
      top: -8px;
      cursor: pointer;
    }
  }
}
.previewWrap {
  display: flex;
  justify-content: center;
}
.stepList {
  padding: 0 0 0 20px;
  .stepItem {
    margin: 0 0 20px 20px;
    .moduleList {
      padding: 0 0 0 20px;
      .moduleItem {
        margin: 20px 0 0;
      }
      .itemList {
        display: inline-block;
        padding: 0 20px;
        border: 1px solid #eee;
        margin: 20px 0 0;
        .itemList__header {
          display: flex;
          .itemList__header__item {
            width: 200px;
            margin-right: 10px;
            text-align: center;
            line-height: 60px;
          }
          .itemList__header__item1 {
            width: 80px;
          }
        }
        .itemList__item {
          display: flex;
          align-items: center;
          margin: 0 0 20px;
          .handleBtns {
            padding: 0 5px;
          }
        }
      }
      .addModuleItem {
        margin: 20px 0 0;
      }
    }
    .stepTitle,
    .moduleTitle {
      display: flex;
      align-items: center;
      .stepSeq {
        margin-right: 10px;
      }
    }
    .iptText {
      width: 200px;
      margin-right: 10px;
    }
    .iptText1 {
      width: 80px;
      margin-right: 10px;
    }
  }
}
.title {
  color: rgba(0, 0, 0, 0.85);
  font-size: 16px;
  font-weight: 500;
  margin-bottom: 16px;
}
.contractNums {
  display: flex;
  align-items: center;
  .contractNums__lab {
    width: 60px;
    margin-right: 20px;
    text-align: right;
  }
  .contractNums__text {
    width: calc(100% -80px);
  }
}
.footer {
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 20px 0;
  .handleBtn {
    margin-right: 20px;
  }
}
</style>
